package com.li.recycleradapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import java.util.List;

/**
 * Author: Li
 * Date: 2017/5/4
 * Description: recyclerView的通用适配器 只适合做一些简单的
 */


public abstract class CommonAdapter<T> extends RecyclerView.Adapter<ViewHolder> {
    public CommonAdapter(List<T> data, int layoutId, Context context, AdapterView.OnItemClickListener onItemClickListener) {
        mData = data;
        mLayoutId = layoutId;
        mContext = context;
        mOnItemClickListener = onItemClickListener;
    }

    private List<T> mData;
    private int mLayoutId;
    private Context mContext;
    private AdapterView.OnItemClickListener mOnItemClickListener;
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(mContext).inflate(mLayoutId,null);
        view.setLayoutParams(new RecyclerView.LayoutParams(-1,-2));
        return new ViewHolder(mContext,view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final int pos=position;
        convert(holder,mData.get(position));
        if (mOnItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onItemClick(null,v,pos,pos);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mData==null?0:mData.size();
    }

    protected abstract void convert(ViewHolder holder,T item);

    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }
}
